﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MemorySiteServer.AuthManage
{
    public class PolicyHandler : AuthorizationHandler<PolicyRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PolicyRequirement requirement)
        {
            var httpContext = (context.Resource as AuthorizationFilterContext).HttpContext;
            if(httpContext.User.Identity.IsAuthenticated)
            {
                //请求Url
                var questUrl = httpContext.Request.Path.Value.ToUpperInvariant();
                var userID = Convert.ToInt64(httpContext.User.Identity.Name);
                var userPermissions = JwtServer.GetUserPermissions(userID);
                if (userPermissions.Any(x => x.Action == questUrl))
                    context.Succeed(requirement);
                else
                    context.Fail();
            }
            return Task.CompletedTask;
        }
    }
}
